package com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.detail.consumer;

import java.util.List;

import com.google.code.irouter.portal.client.AppConstants;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.Detail;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.detail.consumer.target.Command;
import com.google.code.irouter.portal.client.dashboard.main.center.managers.relation.browser.editor.detail.consumer.Source;
import com.google.code.irouter.portal.client.rpc.consumer.ConsumerResult;
import com.google.code.irouter.portal.client.rpc.transponder.TransponderResult;
import com.google.code.irouter.portal.client.rpc.transponder.TransponderService;
import com.google.code.irouter.portal.client.rpc.transponder.TransponderServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.SortDir;
import com.gwtext.client.data.ArrayReader;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.GroupingStore;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.MemoryProxy;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.SortState;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.dd.DragData;
import com.gwtext.client.dd.DragSource;
import com.gwtext.client.dd.DropTarget;
import com.gwtext.client.dd.DropTargetConfig;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridDragData;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GroupingView;

public final class Target extends GridPanel {
	
	private static final AppConstants CONSTANTS = GWT.create(AppConstants.class);
	private final TransponderServiceAsync transponderService = GWT.create(TransponderService.class);
	
	private RecordDef recordDef;
	
	public Target() {
		super();
		this.setId(Target.class.getName());

		recordDef = new RecordDef(  
                new FieldDef[]{  
                        new StringFieldDef("name"),  
                        new StringFieldDef("sender"),
                        new StringFieldDef("consumerKey"),  
                        new StringFieldDef("user"),                          
                        new IntegerFieldDef("maxLength"),
                        new StringFieldDef("key")
                }  
        );  

        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
  
        ArrayReader reader = new ArrayReader(recordDef);  
        GroupingStore store = new GroupingStore();  
        store.setReader(reader);  
        store.setDataProxy(proxy);  
        store.setSortInfo(new SortState("name", SortDir.ASC));  
        store.setGroupField("sender");
        store.load();  
        this.setStore(store);  
  
  
        ColumnConfig[] columns = new ColumnConfig[]{  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_consumer_target_column_name(), 
                		"name", 
                		160, 
                		true, 
                		null, 
                		"target"
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_consumer_target_column_sender(), 
                		"sender", 
                		160,
                		true
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_consumer_target_column_consumerKey(), 
                		"consumerKey", 
                		160,
                		false
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_consumer_target_column_user(), 
                		"user", 
                		160,
                		false
                ),  
                new ColumnConfig(
                		CONSTANTS.com_google_code_irouter_portal_client_dashboard_main_center_managers_relation_browser_editor_detail_consumer_target_column_maxLength(), 
                		"maxLength", 
                		160,
                		false
                ) 
        };  
  
        ColumnModel columnModel = new ColumnModel(columns);  
        this.setColumnModel(columnModel);
        this.setEnableDragDrop(true);
        this.setDdGroup(Source.GROUP);
        this.setStripeRows(true);  
        this.setAutoExpandColumn("name");
        this.setBottomToolbar(new Command());

        
        GroupingView gridView = new GroupingView();  
        gridView.setForceFit(true);  
        gridView.setGroupTextTpl("{text} ({[values.rs.length]} {[values.rs.length > 1 ? \"Items\" : \"Item\"]})");  
        this.setView(gridView);  
        this.setAnimCollapse(false);  
        
        DropTargetConfig cfg = new DropTargetConfig();
        cfg.setdDdGroup(Source.GROUP);

        new DropTarget(this, cfg) {
	        @Override 
	        public boolean notifyDrop(DragSource source, EventObject e, DragData data) {
	        	GridDragData gridDragData = (GridDragData) data;  
	            Record[] records = gridDragData.getSelections();
	            for (int i = 0; i < records.length; i++) {
	            	Record record = records[i];
	            	if(getStore().indexOfId(record.getAsString("key")) == -1) {
	            		Record row = recordDef.createRecord(
		                		new Object[]{
		                				record.getAsString("name"),
		                				record.getAsString("sender"),
		                				record.getAsString("consumerKey"),
		                				record.getAsString("user"),		                				
		                				record.getAsInteger("maxLength"),
		                				record.getAsString("key")
		                		}
		                );
		                getStore().insert(0, row);
	            	}
	            }
	            return true;
	        }
        };
	}
	
	public void remove() {
		Record[] records = this.getSelectionModel().getSelections();
		for(Record record : records) {
			this.getStore().remove(record);
		}
	}
	
	public void reset() {
        MemoryProxy proxy = new MemoryProxy(new Object[0][0]);  
        ArrayReader reader = new ArrayReader(recordDef);  
        GroupingStore store = new GroupingStore();  
        store.setReader(reader);  
        store.setDataProxy(proxy);  
        store.setSortInfo(new SortState("name", SortDir.ASC));  
        store.setGroupField("sender");
        store.load();  
        this.reconfigure(store, this.getColumnModel());
	}
	
	public void load(String id) {
		transponderService.get(id, new AsyncCallback<TransponderResult>() {
			public void onFailure(Throwable caught) {
				// TODO
			}

			public void onSuccess(TransponderResult transponderResult) {
				if(transponderResult != null) {					
					List<ConsumerResult> consumerResultList = transponderResult.getConsumers();
					if(consumerResultList.size() > 0) {
						Object[][] consumerArray = new Object[consumerResultList.size()][6];
						int index = 0;
						for(ConsumerResult consumer : consumerResultList) {
							Object[] consumerItem = new Object[6];
							consumerItem[0] = consumer.getName();
							consumerItem[1] = consumer.getSender();
							consumerItem[2] = consumer.getConsumerKey();
							consumerItem[3] = consumer.getUser();
							consumerItem[4] = String.valueOf(consumer.getMaxLength());
							consumerItem[5] = String.valueOf(consumer.getId());
							consumerArray[index] = consumerItem;
							index++;							
						}
			
						MemoryProxy proxy = new MemoryProxy(consumerArray);						  
				        ArrayReader reader = new ArrayReader(recordDef);  
				        GroupingStore store = new GroupingStore();  
				        store.setReader(reader);  
				        store.setDataProxy(proxy);  
				        store.setSortInfo(new SortState("name", SortDir.ASC));  
				        store.setGroupField("sender");
				        store.load();  
				        
				        reconfigure(store, getColumnModel());
				        ((Detail) Ext.getCmp(Detail.class.getName())).setGlobalEnable(Detail.Children.CONSUMER);
					}
				}				
			}
		});
	}

}
